package com.spdd.mt.app.aop.filter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * 处理跨域问题
 */
@Slf4j
public class CorsFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        log.info("corsFilter access");
        log.info("request uri:{}", req.getRequestURI());

        response.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        // response.setHeader("Content-Type", "application/json; charset=utf-8");
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Accept, Content-Disposition, Authorization");

        if (!req.getRequestURI().contains("users_export") || !req.getMethod().equals("GET")) {
            response.setHeader("Content-Type", "application/json; charset=utf-8");
        }

        filterChain.doFilter(req, response);
    }

}
